import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import router from '@/router'

Vue.use(Vuex)

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

const store = new Vuex.Store({
  modules,
  getters,
  // 在根store的actions中添加
  actions: {
    showExpiredAlert({ commit }, expiredAccounts) {
      return new Promise((resolve) => {
        const message = expiredAccounts.map(account =>
          `<div style="display: flex;gap:150px; width: 100%;margin:20px 0;">
            <span style="width:200px;">账号：${account.account_name}</span>
            <span>过期时间：<span style="color:red">${account.expired_at}</span></span>
          </div>`
        ).join('')

        Vue.prototype.$confirm(message, '过期授权账户提醒', {
          dangerouslyUseHTMLString: true,
          customClass: 'gq-alert',
          confirmButtonText: '去授权',
          showCancelButton: false
        }).then(() => {
          router.push('/account')
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    }
  }
})

export default store
